<template>
  <Teleport to="body">
    <Transition name="modal-fade">
      <div v-if="isOpen" class="modal-overlay" @click="closeOnOverlay ? close() : null">
        <div class="modal-container" @click.stop>
          <div class="modal-header">
            <button class="close-button" @click="close">
              <svg
                xmlns="http://www.w3.org/2000/svg"
                width="24"
                height="24"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
                stroke-linejoin="round"
              >
                <line x1="18" y1="6" x2="6" y2="18"></line>
                <line x1="6" y1="6" x2="18" y2="18"></line>
              </svg>
            </button>
          </div>

          <div class="modal-content">
            <div class="product-header">
              <div class="product-main-image">
                <img :src="nowPic" :alt="product.name" />
              </div>
              <div class="product-price-info">
                <div class="product-price">
                  <span class="currency">¥</span>
                  <span class="amount">{{ nowPrice }}</span>
                </div>
                <div class="installment-info">{{ product.installment }}</div>
              </div>
            </div>

            <div class="product-details">
              <div class="product-id">
                {{ product.category }}
                <span class="id-number">编号: {{ product.id }}</span>
                <span class="list-button">
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    width="16"
                    height="16"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    stroke-width="2"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                  >
                    <line x1="8" y1="6" x2="21" y2="6"></line>
                    <line x1="8" y1="12" x2="21" y2="12"></line>
                    <line x1="8" y1="18" x2="21" y2="18"></line>
                    <line x1="3" y1="6" x2="3.01" y2="6"></line>
                    <line x1="3" y1="12" x2="3.01" y2="12"></line>
                    <line x1="3" y1="18" x2="3.01" y2="18"></line>
                  </svg>
                  列表
                </span>
              </div>

              <div class="product-variants">
                <div
                  v-for="variant in product.variants"
                  :key="variant.id"
                  class="variant-item"
                  :class="[{ 'out-of-stock': variant.stock >= 0 },`data-${variant.id}`]"
                  @click="selectVariant(variant)"
                >
                  <div class="variant-image-container">
                    <img :src="variant.imageUrl" :alt="variant.name" />
                    <div v-if="variant.stock <= 0" class="out-of-stock-overlay">
                      <span>无货</span>
                    </div>

                  </div>
                  <div class="variant-name">{{ variant.name }}</div>
                </div>
              </div>

              <div class="product-options">
                <div class="option-group">
                  <div class="option-label">性别</div>
                  <div class="option-buttons">
                    <button
                      v-for="gender in genders"
                      :key="gender.value"
                      :class="['option-button', { active: selectedGender === gender.value }]"
                      @click="selectedGender = gender.value"
                    >
                      {{ gender.label }}
                    </button>
                  </div>
                </div>

                <div class="option-group">
                  <div class="option-label">数量</div>
                  <div class="quantity-selector">
                    <button
                      class="quantity-button"
                      @click="decrementQuantity"
                      :disabled="quantity <= 1"
                    >
                      −
                    </button>
                    <input
                      type="text"
                      v-model="quantity"
                      class="quantity-input"
                      @input="validateQuantity"
                    />
                    <button class="quantity-button" @click="incrementQuantity">+</button>
                  </div>
                </div>

              </div>

              <div class="action-buttons">
                <button
                  v-if="showAddToCart && !showBuyNow"
                  class="add-to-cart-button"
                  @click="handleAddToCart"
                >
                  确认
                </button>

                <button
                  v-if="showBuyNow && !showAddToCart"
                  class="buy-now-button"
                  @click="handleBuyNow"
                >
                  确认
                </button>
                <div v-if="showAddToCart && showBuyNow" class="cart-buy-buttons">
                  <button class="add-to-cart-button" @click="handleAddToCart">加入购物车</button>

                  <button class="buy-now-button" @click="handleBuyNow">立即购买</button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </Transition>
  </Teleport>
</template>

<script setup>
import { ref, defineProps, defineEmits, nextTick,computed } from 'vue'
import { useRouter } from 'vue-router'
const props = defineProps({
  isOpen: {
    type: Boolean,
    default: false,
  },
  product: {
    type: Object,
    required: true,
  },
  closeOnOverlay: {
    type: Boolean,
    default: true,
  },
  showAddToCart: {
    type: Boolean,
    default: true, // 默认显示“加入购物车”按钮
  },
  showBuyNow: {
    type: Boolean,
    default: true, // 默认显示“立即购买”按钮
  },
  address: {
    type: Object,
    default: null,
  }
})

const nowPic = computed(() => {
  return selectedVariant.value.imageUrl || props.product.mainImage
})

const nowPrice = computed(() => {
  return selectedVariant.value.price || props.product.price
})

const emit = defineEmits(['close', 'add-to-cart', 'buy-now'])

const quantity = ref(1)
const selectedGender = ref('公')
const selectedVariant = ref(props.product.variants[0] || {}) // 默认选中第一个商品变体

let timer = null

const debounce = (fn, delay = 300) => {
  return function (...args) {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn(...args)
    }, delay)
  }
}

const genders = [
  { label: '公', value: '公' },
  { label: '母', value: '母' },
]

const close = () => {
  emit('close')
}

const selectVariant = debounce(async (variant) => {
  if (variant.stock >= 1) {
    selectedVariant.value = variant
    // 等待 DOM 更新后再操作
    await nextTick()
    const variantItems = document.querySelectorAll('.variant-item')
    variantItems.forEach(item => {
      item.classList.remove('selected')
    })
    const selectedItem = document.querySelector(`.data-${variant.id}`)
    selectedItem.classList.add('selected')
  }
}, 100)

const validateQuantity = () => {
  const value = parseInt(quantity.value)
  if (isNaN(value) || value < 1) {
    quantity.value = 1
  } else {
    quantity.value = value
  }
}

const incrementQuantity = () => {
  quantity.value++
}

const decrementQuantity = () => {
  if (quantity.value > 1) {
    quantity.value--
  }
}
const handleAddToCart = () => {
  emit('add-to-cart', {
    product: props.product,
    quantity: quantity.value,
    selectedGender: selectedGender.value,
  })
  close()
}
const router = useRouter()
const handleBuyNow = () => {
// 跳转到订单页面
const orderInfo = {
    product: props.product,
    quantity: quantity.value,
    selectedGender: selectedGender.value,
    selectedVariant: selectedVariant.value,
    totalPrice: nowPrice.value * quantity.value,
    address: props.address
  }
console.log(orderInfo)
  // 跳转到订单页面
  router.push({
    name: 'Order',
    query: {
      orderInfo: JSON.stringify(orderInfo)
    }
  })
  close()
}

</script>

<style lang="scss" scoped>
// Variables
$primary-color: #ff3b30;
$secondary-color: #ff9500;
$border-color: #e0e0e0;
$text-color: #333;
$light-gray: #f5f5f5;
$badge-red: #ff3b30;
$badge-blue: #007aff;

// Modal Animation
.modal-fade-enter-active,
.modal-fade-leave-active {
  transition: opacity 0.3s ease;
}

.modal-fade-enter-from,
.modal-fade-leave-to {
  opacity: 0;
}

// Modal Layout
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: -60px;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-container {
  width: 100%;
  max-width: 500px;
  max-height: 93vh;
  background-color: white;
  border-radius: 12px;
  overflow-y: auto;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  display: flex;
  flex-direction: column;
  position: relative;
}

.modal-header {
  padding: 12px;
  display: flex;
  justify-content: flex-end;
  position: absolute;
  top: 0;
  right: 0;
  z-index: 10;
}

.close-button {
  background: none;
  border: none;
  cursor: pointer;
  color: #333;
  padding: 4px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;

  &:hover {
    background-color: rgba(0, 0, 0, 0.05);
  }
}

.modal-content {
  padding: 0;
}

// Product Header
.product-header {
  display: flex;
  flex-direction: row;
}

.product-main-image {
  position: relative;
  width: 100px;
  height: 100px;
  padding: 10px;
  img {
    width: 100%;
    height: 100%;
    max-height: 200px;
    object-fit: cover;
    display: block;
  }

  .product-badges {
    position: absolute;
    bottom: 30px;
    left: 10px;
    display: flex;
    flex-direction: column;
    gap: 4px;
  }

  .product-guarantee {
    position: absolute;
    bottom: 8px;
    left: 10px;
    background-color: rgba(0, 0, 0, 0.6);
    color: white;
    font-size: 10px;
    padding: 2px 6px;
    border-radius: 4px;

    .guarantee-divider {
      margin: 0 4px;
    }
  }
}

.badge {
  display: inline-block;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
  color: white;

  &.quality-badge {
    background-color: $badge-red;
  }

  &.delivery-badge {
    background-color: $badge-blue;
  }

  &.small {
    font-size: 10px;
    padding: 1px 4px;
  }
}

.product-price-info {
  padding: 12px 16px;

  .product-price {
    display: flex;
    align-items: baseline;
    color: $primary-color;

    .currency {
      font-size: 16px;
      font-weight: bold;
    }

    .amount {
      font-size: 28px;
      font-weight: bold;
    }
  }

  .installment-info {
    color: $secondary-color;
    font-size: 14px;
    margin-top: 4px;
  }
}

// Product Details
.product-details {
  padding: 0 16px 80px;
}

.product-id {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #666;
  margin-bottom: 16px;

  .id-number {
    margin-left: 8px;
  }

  .list-button {
    margin-left: auto;
    display: flex;
    align-items: center;
    gap: 4px;
    color: #666;
  }
}

// Product Variants
.product-variants {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 8px;
  margin-bottom: 20px;
}

.variant-item {
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid $border-color;

  &.out-of-stock {
    opacity: 0.8;
  }
}

// 选中状态
.selected {
    border-color: #7C4DFF;
    background: rgba(124, 77, 255, 0.05);
  }


.variant-image-container {
  position: relative;
  width: 100%;
  padding-top: 100%; // 1:1 Aspect ratio

  img {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .out-of-stock-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-weight: bold;
  }

  .variant-badges {
    position: absolute;
    top: 4px;
    left: 4px;
    display: flex;
    flex-direction: column;
    gap: 2px;
  }

  .favorite-button {
    position: absolute;
    bottom: 4px;
    right: 4px;
    background-color: rgba(0, 0, 0, 0.5);
    border-radius: 50%;
    width: 24px;
    height: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
  }
}

.variant-name {
  padding: 8px;
  text-align: center;
  font-size: 12px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

// Product Options
.option-group {
  margin-bottom: 16px;
}

.option-label {
  font-size: 14px;
  margin-bottom: 8px;
}

.option-buttons {
  display: flex;
  gap: 8px;
}

.option-button {
  padding: 8px 24px;
  border: 1px solid $border-color;
  border-radius: 20px;
  background-color: white;
  font-size: 14px;
  cursor: pointer;

  &.active {
    background-color: #fff0f0;
    border-color: $primary-color;
    color: $primary-color;
  }
}

.quantity-selector {
  display: flex;
  align-items: center;
  width: fit-content;
  border: 1px solid $border-color;
  border-radius: 4px;
}

.quantity-button {
  width: 36px;
  height: 36px;
  background-color: $light-gray;
  border: none;
  font-size: 18px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;

  &:disabled {
    color: #ccc;
    cursor: not-allowed;
  }
}

.quantity-input {
  width: 50px;
  height: 36px;
  border: none;
  border-left: 1px solid $border-color;
  border-right: 1px solid $border-color;
  text-align: center;
  font-size: 14px;
}

.payment-terms {
  margin-bottom: 20px;

  .payment-label {
    background-color: #fff0f0;
    color: $primary-color;
    padding: 2px 8px;
    border-radius: 4px;
    font-size: 14px;
    margin-right: 8px;
  }

  .payment-value {
    color: $secondary-color;
    font-size: 14px;
  }
}

// Action Buttons
.cart-buy-buttons {
  width: 100%;
  display: flex;
  gap: 10px;
}

.action-buttons {
  display: flex;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 7px;
  gap: 12px;
  background: #fff;
}

.add-to-cart-button {
  flex: 1;
  padding: 12px;
  border: none;
  border-radius: 24px;
  background-color: #f2effe;
  color: #333;
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;

  &:hover {
    background-color: red;
    color: white;
  }
}

.buy-now-button {
  flex: 1;
  padding: 12px;
  border: none;
  border-radius: 24px;
  background-color: $primary-color;
  color: white;
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;

  &:hover {
    background-color: red;
  }
}
</style>
